package petrochina.company.electric.ui.dialog;

import android.content.Context;
import android.content.res.Resources;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import androidx.appcompat.widget.AppCompatButton;
import androidx.appcompat.widget.AppCompatImageView;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleOwner;

import com.hjq.base.BaseDialog;
import com.hjq.http.EasyHttp;
import com.hjq.http.listener.HttpCallback;
import com.hjq.http.listener.OnHttpListener;

import petrochina.company.electric.R;
import petrochina.company.electric.aop.SingleClick;
import petrochina.company.electric.http.api.BackgroundTaskConfirmApi;
import petrochina.company.electric.http.api.TaskDetailStepApi;
import petrochina.company.electric.http.model.HttpData;
import petrochina.company.electric.ui.activity.TaskDetailActivity;

/**
 * 任务-后台确认弹框
 */
public final class TaskDistributeConfirmDialog {

    public static final class Builder
            extends BaseDialog.Builder<Builder>
            implements
            View.OnLayoutChangeListener, Runnable, LifecycleOwner, OnHttpListener {

        @SuppressWarnings("rawtypes")
        @Nullable
        private OnListener mListener;
        private boolean mAutoDismiss = true;

        private Context mContext;

        private final TextView tv_content;
        private final AppCompatButton btn_cancel, btn_confirm;


        public Builder(Context context) {
            super(context);
            mContext = context;
            initData();
            setContentView(R.layout.task_distribute_confirm_dialog);
            setAnimStyle(BaseDialog.ANIM_BOTTOM);
            tv_content = findViewById(R.id.tv_content);
            btn_cancel = findViewById(R.id.btn_cancel);
            btn_confirm = findViewById(R.id.btn_confirm);
            setOnClickListener(btn_cancel, btn_confirm);
        }

        /**
         * 根据后台状态更改UI
         *
         * @param type
         */
        private void resetStatusView(int type) {
            String currentState = "错误";
            switch (type) {
                case -1:
                    currentState = "错误";
                    break;
                case 1:
                    currentState = "分";
                    break;
                case 2:
                    currentState = "合";
                    break;
            }
//            mTvBleDeviceStatusCurrent.setText("当前状态：" + (type == 1 ? "分" : "合"));

        }

        @Override
        public void show() {
            super.show();
//            if (mTaskPowerResult != null) {
//                mTvStepContent.setText(mTaskPowerResult.getOperInfo());
//                mTvBleDeviceStatus.setText("预期状态：" + (mTaskPowerResult.getOperType() == 1 ? "分" : "合"));
//                EasyHttp.get(((TaskDetailActivity) mContext))
//                        .api(new BackgroundTaskConfirmApi().setType(mType).setStepId(mTaskPowerResult.getId()))
//                        .request(new HttpCallback<HttpData<BackgroundTaskConfirmApi.Bean>>(this) {
//
//                            @Override
//                            public void onSucceed(HttpData<BackgroundTaskConfirmApi.Bean> result) {
//                                try {
//                                    resetStatusView(Integer.parseInt(result.getData().getStatus()));
//                                } catch (Exception e) {
//                                }
////                            requireActivity().finish();
//                            }
//
//                            @Override
//                            public void onFail(Exception e) {
//                                super.onFail(e);
////                                resetStatusView(mTaskPowerResult.getOperType() == 1 ? 2 : 1);
//                                resetStatusView(-1);
//                                // 比对失败上报
//                                if (mListener == null) {
//                                    return;
//                                }
//                                mListener.onSelected(getDialog(), 1, null);
//                            }
//                        });
//            } else {
//                dismiss();
//            }
        }

        private void initData() {

        }

        @Override
        public Builder setGravity(int gravity) {
            switch (gravity) {
                // 如果这个是在中间显示的
                case Gravity.CENTER:
                case Gravity.CENTER_VERTICAL:
                    // 不显示取消按钮
                    setCancel(null);
                    // 重新设置动画
                    setAnimStyle(BaseDialog.ANIM_SCALE);
                    break;
                default:
                    break;
            }
            return super.setGravity(gravity);
        }

        @Override
        public Builder addOnDismissListener(@NonNull BaseDialog.OnDismissListener listener) {
            return super.addOnDismissListener(listener);
        }

        /**
         * 销毁,释放资源
         */
        @Override
        public void dismiss() {
            mContext = null;
            super.dismiss();
        }

//        public Builder setData(TaskDetailStepApi.Bean taskPowerResult) {
//            this.mTaskPowerResult = taskPowerResult;
//            return this;
//        }

//        public Builder setType(int type) {
//            this.mType = type;
//            return this;
//        }

        public Builder setCancel(@StringRes int id) {
            return setCancel(getString(id));
        }

        public Builder setCancel(CharSequence text) {
//            mBleOptStatusButton.setText(text);
            return this;
        }

        public Builder setAutoDismiss(boolean dismiss) {
            mAutoDismiss = dismiss;
            return this;
        }

        @SuppressWarnings("rawtypes")
        public Builder setListener(OnListener listener) {
            mListener = listener;
            return this;
        }

        @SingleClick
        @Override
        public void onClick(View view) {
            if (mAutoDismiss) {
                dismiss();
            }
//            if (view == mIvBleSearchCloser) {
//                if (mListener == null) {
//                    return;
//                }
//                mListener.onCancel(getDialog());
//            } else if (view == mBleOptStatusButton) {
//                if (mListener == null) {
//                    return;
//                }
//                mListener.onSelected(getDialog(), 0, (mTaskPowerResult.getOperType() == 1 ? "分" : "合"));
//            } else if (view == mBtnBleOptCancel) {
//                if (mListener == null) {
//                    return;
//                }
//                mListener.onCancel(getDialog());
//            } else if (view == mBtnBleOptReconnect) {
//                EasyHttp.get(((TaskDetailActivity) mContext))
//                        .api(new BackgroundTaskConfirmApi().setType(mType).setStepId(mTaskPowerResult.getId()))
//                        .request(new HttpCallback<HttpData<BackgroundTaskConfirmApi.Bean>>(this) {
//
//                            @Override
//                            public void onSucceed(HttpData<BackgroundTaskConfirmApi.Bean> result) {
//                                try {
//                                    resetStatusView(Integer.parseInt(result.getData().getStatus()));
//                                } catch (Exception e) {
//                                }
////                                resetStatusView(mTaskPowerResult.getOperType());
////                            requireActivity().finish();
//                            }
//
//                            @Override
//                            public void onFail(Exception e) {
//                                super.onFail(e);
////                                resetStatusView(mTaskPowerResult.getOperType() == 1 ? 2 : 1);
//                                resetStatusView(-1);
//                                if (mListener == null) {
//                                    return;
//                                }
//                                mListener.onSelected(getDialog(), 1, null);
//                            }
//                        });
//            }
        }

        /**
         * {@link View.OnLayoutChangeListener}
         */
        @Override
        public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
            // 这里一定要加延迟，如果不加在 Android 9.0 上面会导致 setLayoutParams 无效
            post(this);
        }

        @Override
        public void run() {

        }

        /**
         * 获取屏幕的高度
         */
        private int getScreenHeight() {
            Resources resources = getResources();
            DisplayMetrics outMetrics = resources.getDisplayMetrics();
            return outMetrics.heightPixels;
        }

        @NonNull
        @Override
        public Lifecycle getLifecycle() {
            return null;
        }

        @Override
        public void onSucceed(Object result) {

        }

        @Override
        public void onFail(Exception e) {

        }
    }

    public interface OnListener<T> {

        /**
         * 选择条目时回调
         */
        void onSelected(BaseDialog dialog, int position, T t);

        /**
         * 点击取消时回调
         */
        default void onCancel(BaseDialog dialog) {
        }
    }

    private static byte[] getWriteData() {

        String s1 = "010300060001640B";

        String crc = getCRC(s1);

        Log.d("bobowa", "s4=" + s1);

        return hexStringToBytes(s1 + crc);

    }

    /**
     * 字符串转换为16进制字符串
     * <p>
     * 设备号转hex命令
     *
     * @param s
     * @return
     */

    public static String stringToHexString(String s) {

        String str = "";

        for (int i = 0; i < s.length(); i++) {

            int ch = s.charAt(i);

            String s4 = Integer.toHexString(ch);

            str = str + s4;

        }

        return str;

    }

    public static String getCRC(String data) {

        data = data.replace(" ", "");

        int len = data.length();

        if (!(len % 2 == 0)) {

            return "0000";

        }

        int num = len / 2;

        byte[] para = new byte[num];

        for (int i = 0; i < num; i++) {

            int value = Integer.valueOf(data.substring(i * 2, 2 * (i + 1)), 16);

            para[i] = (byte) value;

        }

        return getCRC(para);

    }

    public static String getCRC(byte[] bytes) {

//CRC寄存器全为1

        int CRC = 0x0000ffff;

//多项式校验值

        int POLYNOMIAL = 0x0000a001;

        int i, j;

        for (i = 0; i < bytes.length; i++) {

            CRC ^= ((int) bytes[i] & 0x000000ff);

            for (j = 0; j < 8; j++) {

                if ((CRC & 0x00000001) != 0) {

                    CRC >>= 1;

                    CRC ^= POLYNOMIAL;

                } else {

                    CRC >>= 1;

                }

            }

        }

//结果转换为16进制

        String result = Integer.toHexString(CRC).toUpperCase();

        if (result.length() != 4) {

            StringBuffer sb = new StringBuffer("0000");

            result = sb.replace(4 - result.length(), 4, result).toString();

        }

//交换高低位

        return result.substring(2, 4) + result.substring(0, 2);

    }

    /**
     * String转换成每2位的数组
     *
     * @param hexString
     * @return
     */

    public static byte[] hexStringToBytes(String hexString) {

        Log.d("bobowa", "hexStringToBytes=" + hexString);

        if (hexString == null || hexString.equals("")) {

            return null;

        }

        hexString = hexString.toUpperCase();

        int length = hexString.length() / 2;

        char[] hexChars = hexString.toCharArray();

        byte[] d = new byte[length];

        for (int i = 0; i < length; i++) {

            int pos = i * 2;

            d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));

        }

        return d;

    }

    public static byte charToByte(char c) {

        return (byte) "0123456789ABCDEF".indexOf(c);

    }
    /* *

     * Convert byte[] to hex string.这里我们可以将byte转换成int，然后利用Integer.toHexString(int)

     *来转换成16进制字符串。

     * @param src byte[] data

     * @return hex string

     */

    public static String bytesToHexString(byte[] src) {
        StringBuilder stringBuilder = new StringBuilder("");
        if (src == null || src.length <= 0) {
            return null;
        }
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }
}